package com.meila.cms.web;

import java.io.PrintWriter;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.meila.cms.model.CmsException;
import com.meila.cms.model.UserModel;
import com.meila.cms.util.HttpUtils;



public class AuthInterceptor extends HandlerInterceptorAdapter {
	
	private Logger logger  = LoggerFactory.getLogger(getClass());
	
	/**
	 * 不拦截的后缀
	 */
	private List<String> excludeMappingUrl;
	
	/**
	 * 处理时间  线程绑定
	 */
	private ThreadLocal<Long> dealTimeThradeLocal = new ThreadLocal<Long>();
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		HttpSession session = request.getSession();
 
    	//未登入前的资源文件不过滤
	    String path1 = "/before";
	    String path2 = "/resources";
		
		long startTime = System.currentTimeMillis();
		dealTimeThradeLocal.set(startTime);
		
		String url = request.getRequestURI();
		String postFix = null;
		if(!StringUtils.isEmpty(url)){
			// 静态文件
			int index = url.lastIndexOf(".");
			if(index > -1){
				postFix = url.substring(index);
			}
			
			if(!StringUtils.isEmpty(postFix) && excludeMappingUrl.contains(postFix)){
				// 静态文件默认处理
				return true;
			}else{
				UserModel user = (UserModel)session.getAttribute("loginUser");
				
				//导出pdf时 url.openConnection()获取不到session但此时不用过滤
			    String export= request.getParameter("export");
 
				if((user==null&&!request.getServletPath().contains(path1) &&
						       !request.getServletPath().contains(path2))) {
					
					if(!"true".equals(export)){
					 
						if(HttpUtils.isAjaxRequestInternal(request,response)){
							 response.setHeader("sessionstatus","timeout");
							 response.setStatus(403);
						     //向http头添加登录的url
							 response.addHeader("loginPath", request.getContextPath()+"/before/login");
							 
						    return super.preHandle(request, response, handler);
						}else{
							 
							response.sendRedirect(request.getContextPath()+"/before/login"); 
						}
						
					}
					
				
				}else{
				    	if(user!=null && !user.isAdmin()){
							Set<String> actions = (Set<String>)session.getAttribute("allActions");
							//防止js动态请求html报 cannot be cast to org.springframework.web.method.HandlerMethod 
							if (handler instanceof HandlerMethod) {
								HandlerMethod hm = (HandlerMethod)handler;
								String aname = hm.getBean().getClass().getName()+"."+hm.getMethod().getName();
								if(!actions.contains(aname)) throw new CmsException("没有权限访问该功能");
							}
					
				    	}

					 
				}
			}
		}
 
		return super.preHandle(request, response, handler);
	}
	
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //To change body of implemented methods use File | Settings | File Templates.
    	if(!isStaticFile(httpServletRequest.getRequestURI())){
			long endTime = System.currentTimeMillis();
			long starTime = dealTimeThradeLocal.get();
			logger.info("本次请求["+httpServletRequest.getRequestURI()+"]处理时间："+(endTime-starTime)+"ms");
		}
		
    }
	
	public boolean isStaticFile(String url){
		if(!StringUtils.isEmpty(url)){
			// 静态文件
			int index = url.lastIndexOf(".");
			String postFix = null;
			if(index > -1){
				postFix = url.substring(index);
			}
			
			if(!StringUtils.isEmpty(postFix) && excludeMappingUrl.contains(postFix)){
				// 静态文件默认处理
				return true;
			}
		}
		
		return false;
	}
    
    
	public List<String> getExcludeMappingUrl() {
		return excludeMappingUrl;
	}

	public void setExcludeMappingUrl(List<String> excludeMappingUrl) {
		this.excludeMappingUrl = excludeMappingUrl;
	}
}
